<template>
	<view>
		<view>
			<block v-if="form.video" >
				<video id="myVideo" style="width: 100%; height: 350rpx;" :poster="form.video+'?vframe/png/offset/5'" :src="form.video" controls></video>
			</block>
			<block v-if="showlist" >
				<scroll-view scroll-x="true" class="scroll-row w-100">
					<view  v-for="(item, index) in videoList" :key="index" class="scroll-row-item px-1 font-sm border"
					 :class="item.id===form.id?'bg-main':''"
					@click="itemClick(item)" style="width: 200rpx; height: 100rpx;">
						<view class="text-ellipsis text-center" style="width: 200rpx;height: 100rpx; line-height: 100rpx;">{{item.title}}</view>
					</view>
				</scroll-view>
				<view class="flex align-center justify-center text-center border-bottom" style="height: 100rpx;">
					<view class="flex-1 font-sm" hover-class="bg-hover-light" style="height: 100rpx; line-height: 100rpx;" @click="modifyVideo(1)">修改</view>
					<view class="flex-1 font-sm" hover-class="bg-hover-light" style="height: 100rpx; line-height: 100rpx;" @click="modifyVideo(2)">删除</view>
				</view>
			</block>
			<view class="flex justify-center px-2">
				<uni-forms class="w-100" ref="form" :modelValue="form" :rules="rules1" style="padding: 20rpx;" v-show="isEdit" validateTrigger="bind">
					<uni-forms-item label="视频" name="video">
						<text class="font text-main" @tap="upload" style="line-height: 70rpx;">点击{{form.video?'更新':'添加'}}视频</text>
						<cmd-progress v-if="(percent >= 0)" :percent="percent"></cmd-progress>
						<uni-easyinput v-show="false" style="height: 0rpx;" name="video" type="number" v-model="form.video" placeholder="请输入集号" />
					</uni-forms-item>
					<uni-forms-item label="集号" name="no">
						 <uni-easyinput name="no" type="number" v-model="form.no" placeholder="请输入集号" />
					</uni-forms-item>
					<uni-forms-item label="标题" name="title">
						 <uni-easyinput name="title" type="text" v-model="form.title" placeholder="请输入标题" />
					</uni-forms-item>
					<uni-forms-item label="描述" name="description">
						 <uni-easyinput name="description" type="textarea" v-model="form.description" placeholder="请输入描述" />
					</uni-forms-item>
					<view class="flex align-center justify-center text-center border-bottom" style="height: 100rpx;">
						<view class="flex-1 font-sm bg-main" hover-class="bg-main-hover" style="height: 100rpx; line-height: 100rpx;" @click="formSubmit">完成</view>
						<view class="flex-1 font-sm" hover-class="bg-hover-light" style="height: 100rpx; line-height: 100rpx;" @click="modifyVideo(0)">取消</view>
					</view>
				</uni-forms>
			</view>
			<!-- 分割线 -->
			<view class="f-divider"></view>
			<!-- 按钮 -->
			<view hover-class="bg-main-hover" class="bg-main text-white text-center" v-show="!isEdit"
			style="height: 80rpx; line-height: 80rpx;" @click="addVideo">
				<text class="iconfont iconjia" style="font-size: 20rpx;"></text>
				<text class="font-sm ml-1">添加新章节</text>
			</view>
			
		</view>
	</view>
</template>

<script>
	import cmdProgress from "@/components/cmd-progress/cmd-progress.vue"
	// #ifndef H5
	import VodUploader from '@/common/vod-wx-sdk-v2.js';
	// #endif

	export default {
		components: {cmdProgress},
		data() {
			return {
				percent: -1, // 视频上传进度
				rules1: {
					// 对name字段进行必填验证
					video: {rules: [{required: true,errorMessage: '请上传视频'}]},
					title: {rules: [{required: true,errorMessage: '请填写标题'}]},
					no: {rules: [{required: true,errorMessage: '请填写集号'}]},
				},
				video:null,
				isEdit:false,// 页面处于编辑模式，还是查看模式
				videoList:[],
				
				form:{
					id:0,
					video:null,//视频
					no:null,//集号，第几集
					title:"新标题",//封面
					description:"这是描述"//描述
				}
			}
		},
		computed: {
			showlist() {
				return this.videoList.length > 0 && ( (this.isEdit && this.form.id) || !this.isEdit) 
			},
		},
		onLoad(e) {
			//console.log(e)
			if(e.id){
				this.getVideo(e.id).then(res=>{
					this.video = res;
					this.getData();
				}).catch(err=>{
					uni.showToast({
						title:err,
						icon:'none'
					});
					setTimeout(()=>{
						uni.navigateBack()
					},500)
				})
			}
		},
		methods: {
			// 获取作品
			getVideo(id){
				return this.$H.get(`/video_get/${id}`);
			},
			// 获取该作品下的全部视频
			getData(){
				return this.$H.get('/video_detail_list?video_id='+this.video.id).then(res=>{
					this.videoList = res;
					if(res.length > 0){
						this.form.id = res[0].id;
						this.form.video = res[0].video;
						this.form.title = res[0].title;
						this.form.no = res[0].no;
						this.form.description = res[0].description;
					}
				})
			},
			//编辑视频，flag:0 取消编辑  flag:1 编辑视频  flag:2 删除视频
			modifyVideo(flag){
				if(flag > 0 && !this.form.id >0 ){
					uni.showToast({
						title:'请先选择视频',
						icon:'none'
					})
					return
				}
				//如果是编辑或者取消
				if(flag <= 1){
					this.isEdit = flag&&true;
					if(flag === 0){
						this.clearForm()
					}
				}
				//删除视频
				else{
					uni.showModal({
						title:'提示',
						content:'确认删除该视频',
						success: (res) => {
							if(res.confirm){
								//console.log('用户点击确定')
								this.$H.post('/video_detail/destroy',{id:this.form.id},{token:true}).then(res=>{
									// var aitem = this.videoList.find((item)=>{
									// 	return item.id === this.form.id
									// })
									// this.videoList.pop(aitem)
									// 【特别注意】：删除数组中某一数据的方式
									for (let i = 0; i < this.videoList.length; i++) { 
										if (this.videoList[i].id === this.form.id){
											this.videoList.splice(i,1);
											break;
										} 
									}
									this.form.id = 0
									this.clearForm()
									uni.showToast({title:'删除视频成功',icon:'none'})
								})
							} else if(res.cancel){
								//console.log('用户点击取消')
							}
						}
					})
					this.isEdit = false
				}
				
			},
			clearForm(){
				if(this.form.id > 0){
					// 代表是修改视频时的取消，则应该将form全部清空
					var aitem = this.videoList.find((i)=>{
						return this.form.id === i.id
					})
					if(aitem){
						this.form.id = aitem.id
						this.form.no = aitem.no
						this.form.video = aitem.video
						this.form.title = aitem.title
						this.form.description = aitem.description
					}
				} else {
					// 代表是新增视频时的取消，则应该将form全部清空
					this.form.video = ''
					this.form.title = ''
					this.form.description = ''
					this.form.id = 0
					//取最大集数
					let no = 0
					this.videoList.forEach(item=>{
						if(item.no > no) {
							no = item.no
						}
					})
					this.form.no = no+1;
				}
			},
			addVideo(){
				// 注意，程序通过this.form.id来判断是修改模式下的清空，还是编辑模式下的清空
				this.form.id = 0;
				this.clearForm()
				this.isEdit = true
			},
			itemClick(item){
				this.form = {...item}
				//console.log(JSON.stringify(this.form))
			},
			formSubmit(e) {
			    //表单验证
				this.$refs.form.validate().then(res=>{
					// console.log('验证成功，form数据信息：', res);
					this.isEdit = false;
					this.modifyItem(this.form)
				}).catch(err =>{
					console.log('验证失败，错误信息：', err);
					uni.showToast({
						title:'验证失败',
						icon:"none"
					})
				})
			},
			modifyItem(item){
				if(item.id > 0){
					this.$H.post('/video_detail/'+item.id,{
						url:this.form.video,
						no: parseInt(this.form.no),
						title: this.form.title,
						description : this.form.description,
						video_id:this.video.id
					},{token:true}).then(res=>{
						//修改
						var aitem = this.videoList.find((i)=>{
							return item.id === i.id
						})
						if(aitem){
							aitem.id = res.id
							aitem.no = res.no
							aitem.video = res.url
							aitem.title = res.title
							aitem.description = res.description
							uni.showToast({title:"修改成功", icon:"none"});
						}
					})
				} else {
					this.$H.post('/video_detail',{
						url:this.form.video,
						no: parseInt(this.form.no),
						title: this.form.title,
						description : this.form.description,
						video_id:this.video.id
					},{token:true}).then(res=>{
						this.form = {
							id:res.id,
							no:res.no,
							title:res.title,
							description:res.description,
							video:res.url
						}
						this.videoList.push({
							id:res.id,
							no:res.no,
							title:res.title,
							description:res.description,
							video:res.url
						})
						uni.showToast({title:"新增成功", icon:"none"});
					}).catch(err=>{
						uni.showToast({title:err, icon:"none"});
						console.log(err); 
					})
				}
			},
			upload(){
				uni.chooseVideo({
					count: 1,
					compressed:true,
					sourceType: ['camera', 'album'],
					success: (res)=> {
						// #ifdef H5
						let getSignature = (callback) => {
							return this.$H.post('/vod/sign',{},{
								token:true
							}).then(res=>{
								return res
							})
						}
						// #endif
						
						// #ifndef H5
						let getSignature = (callback) => {
							this.$H.post('/vod/sign',{},{
								token:true
							}).then(res=>{
								callback(res);
							})
						}
						// #endif
						
						// 生成唯一名称
						let mediaName = this.genID(12)
						uni.showLoading({
							title: '上传中...',
							mask: false
						});
						
						// #ifdef H5
						const tcVod = new TcVod.default({
						  getSignature: getSignature
						})
						const uploader = tcVod.upload({
						  mediaFile: res.tempFile,
						})
						uploader.on('media_progress',(info)=> {
						  console.log(info.percent) // 进度
						  this.percent = parseInt(info.percent*100)
						})
						uploader.done().then((doneResult)=>{
							// 上传后的视频链接
							let temp = doneResult.video.url
							if(temp.indexOf('https') === -1) {
								temp = temp.replace('http','https')
							}
							this.form.video = temp
							console.log(temp)
							uni.hideLoading()
							this.percent = -1
						}).catch((err)=>{
							console.log(err);
							uni.hideLoading()
							uni.showToast({
								title: '上传失败',
								icon: 'none'
							});
						})
						// #endif
						
						// #ifndef H5
						VodUploader.start({
							mediaFile: res, 
							getSignature: getSignature,
							mediaName: mediaName,
							success: (result)=>{
								console.log('success');
								console.log(result);
							},
							error:(result)=> {
								uni.hideLoading()
								console.log('错误信息：' + result.data.message);
								let msg = result.data.code === 10002 ? '腾讯云点播子应用ID配置不正确，请修改自己部署的后端配置。（注意：老师提供的线上测试接口上传视频功能已关闭，请自己下载群文件完整后端代码跟着课程部署）' : result.data.message
								uni.showModal({
									title: '上传失败',
									content: msg,
									showCancel: false
								});
							},
							progress:(result)=> {
								console.log('progress');
								console.log(result);
								this.percent = parseInt(result.percent*100)
							},
							finish: (result)=>{
								// 上传后视频链接
								let temp = result.videoUrl
								if(temp.indexOf('https') === -1) {
									temp = temp.replace('http','https')
								}
								this.form.video = temp
								console.log(temp)
								uni.hideLoading()
								this.percent = -1
							}
						});
						// #endif
					},
					fail: (err) => {
						console.log(err);
					}
				})
			},
			// 生成唯一ID
			genID(length){
			    return Number(Math.random().toString().substr(3,length) + Date.now()).toString(36);
			}
		}
	}
</script>

<style>
scroll-view ::-webkit-scrollbar {
display: none !important;
width: 0 !important;
height: 0 !important;
-webkit-appearance: none;
background: transparent;
}
</style>
